<?php
/**
 * 用户登陆类库.
 * User: mac
 * Date: 2018/6/20
 * Time: 09:42
 */

namespace app\api\controller;

use app\common\lib\IAuth;

class User extends Api
{
    /**
     * 获取用户的openid
     */
    public function loginByOpenid(){
        //获取POST提交的code
        $js_code = input('post.code');

        //查看有没有推荐人openid
        $js_inviteOpenId = input('post.inviteOpenId');

        //判定提交的code是否存在
        if(!$js_code){
            return show(false,0,'提交的code不合法');
        }

        //获取小程序的AppId和AppSecret
        $app = $this->wecaht;
        //拼接请求地址
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

        //替换
        $curl = sprintf($url,$app['appid'],$app['appsecret'],$js_code);

        //发起curl请求
        $result = json_decode(self::request($curl),true);
        //判定是否获取到数据
        if(!$result && !is_array($result)){
            return show(false);
        }

        //返回数据给前端
        try{
            $user = model("Users")->getUsersByOpenId($result['openid']);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }

        if(!$user){
            $data = array(
                'openid'=>$result['openid'],
                'status'=>1,
                'register_time' => time(),
                'invite_id' => $js_inviteOpenId,
            );
            try{
                $id = model("Users")->add($data);
            }catch(\Exception $e){
                return show(false,0,$e->getMessage());
            }
        }
        $res = array(
            'openid' => $result['openid'],
            'id' => $user ? $user['id'] : $id,
            'key' => $result['session_key'],
            'time' => IAuth::get13Time(),
        );
        $token = IAuth::setToken($res);
        return show(true,0,'',self::res($token,$result['openid']));

    }
    //登陆操作
    public function login(){

        //获取 session_key 和 openid
        $arr = $this->cache;

        //数据签名校验
        $signature = input('post.signature');
        $rawData = input('post.rawData');
        $signature2 = sha1($rawData.$arr['key']);
        if($signature != $signature2){
            echo "数据签名验证失败";die;
        }

        //获取敏感数据，需要对接口返回的加密数据( encryptedData )进行对称解密
        $encryptedData = input("post.encryptedData");
        $iv = input('post.iv');
        $pc = new WxBizDataCrypt($this->wecaht['appid'],$arr['key']);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        //其中$data包含用户的所有数据
        if ($errCode != 0) {
            echo '解密数据失败！';die;
        }

        //生成第三方token
        $res = array(
            'time' => IAuth::get13Time(),
            'id' => $arr['id'],
            'is_login' => true
        );
        $token = IAuth::setToken($res);

        //入库操作
        $result = json_decode($data,true);
        $result = array(
            'name' => $result['nickName'],
            'gender' => $result['gender'],
            'image_url' => $result['avatarUrl'],
        );

        //根据ID修改用户的资料
        try{
            model("Users")->UpdateUsersById($arr['id'],$result);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }
        //返回数据
        return show(true,0,'',self::res($token,$arr['openid'],$result['avatarUrl'],$result['nickName']));
    }


    //用户登陆返回数据
    public static function res($key,$id,$img=null,$name = '未知'){
        $data = array(
            'Key' => $key,
            'headImg' => $img,
            'Openid' => $id,
            'UserName' => $name
        );
        return $data;
    }

    //

}